from rest_framework import serializers

from projects.models import Projects
from .models import Configures
from utils.validates import whether_existed_project_id





class ConfigureSerializer(serializers.ModelSerializer):
    """
    配置序列化器
    """
    project = serializers.StringRelatedField(help_text='项目名称')
    project_id = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(),
                                                    help_text='项目ID')
    class Meta:
        model = Configures
        fields = ('id', 'name', 'project', 'project_id', 'author', 'request')
        extra_kwargs = {
            'request': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        project = validated_data.pop('project_id')
        validated_data['project'] = project
        configures = Configures.objects.create(**validated_data)
        return configures

    def update(self, instance, validated_data):
        if 'project_id' in validated_data:
            project = validated_data.pop('project_id')
            validated_data['project'] = project
        return super().update(instance, validated_data)





